package com.woniuxy.java102vuecli.controller;

import com.woniuxy.java102vuecli.exception.EmailExistsException;
import com.woniuxy.java102vuecli.exception.EnameNotExistsException;
import com.woniuxy.java102vuecli.exception.PasswordIncorrectException;
import com.woniuxy.java102vuecli.exception.VerifyCodeErrorException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author author
 * @Create 2023-09-18 15:42
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler
    public ResponseResult doException(Exception e){
        e.printStackTrace();
        log.info("exception={}", e.getClass());
        log.info("exception={}", e.getMessage());
//        return new ResponseResult(500,"error",e.getMessage());
        return new ResponseResult(500,"error","服务器错误，稍后再试,"+e.getMessage());
    }

    @ExceptionHandler
    public ResponseResult doVerifyCodeErrorException(VerifyCodeErrorException e){
        return new ResponseResult(500,"error",e.getMessage());
    }
    @ExceptionHandler
    public ResponseResult doEnameNotExistsException(EnameNotExistsException e){
        return new ResponseResult(500,"error",e.getMessage());
    }
    @ExceptionHandler
    public ResponseResult doPasswordIncorrectException(PasswordIncorrectException e){
        return new ResponseResult(500,"error",e.getMessage());
    }
    @ExceptionHandler
    public ResponseResult doEmailExistsException(EmailExistsException e){
        return new ResponseResult(500,"error",e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult doMethodArgumentNotValidException(MethodArgumentNotValidException e){
        //后端验证
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errors=new HashMap<>();
//        if (bindingResult.getFieldErrorCount()>0) {
//            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//            for(FieldError fieldError : fieldErrors){
//                errors.put(fieldError.getField(), fieldError.getDefaultMessage());
//            }
            bindingResult.getFieldErrors().forEach(item -> errors.put(item.getField(), item.getDefaultMessage()));
            return new ResponseResult(100,"valid error",errors);
//        }
    }
}
